<template>
	<div class="app-container">
		<el-form
			v-show="showSearch"
			ref="queryForm"
			:model="queryParams"
			:inline="true"
			label-width="68px"
		>
			<el-form-item :label="$t('calling.name')" prop="name">
				<el-input
					v-model="queryParams.name"
					:placeholder="$t('calling.nameInput')"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item :label="$t('elButton.establishTime')">
				<el-date-picker
					v-model="dateRange"
					size="small"
					style="width: 240px"
					value-format="yyyy-MM-dd"
					type="daterange"
					range-separator="-"
					:start-placeholder="$t('elButton.startTime')"
					:end-placeholder="$t('elButton.endTime')"
				/>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					icon="el-icon-search"
					size="mini"
					@click="handleQuery"
					>{{ $t('elButton.search') }}
				</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
					$t('elButton.reset')
				}}</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					v-hasPerm="['dataset_add']"
					type="primary"
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
					>{{ $t('elButton.add') }}
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					v-hasPerm="['dataset_edit']"
					type="success"
					icon="el-icon-edit"
					size="mini"
					:disabled="single"
					@click="handleEdit"
					>{{ $t('elButton.change') }}
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					v-hasPerm="['dataset_del']"
					type="danger"
					icon="el-icon-delete"
					size="mini"
					:disabled="multiple"
					@click="handleDel"
					>{{ $t('elButton.delete') }}
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					v-hasPerm="['dataset_export']"
					type="warning"
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
					>{{ $t('elButton.export') }}
				</el-button>
			</el-col>
			<div class="top-right-btn">
				<el-tooltip
					class="item"
					effect="dark"
					:content="$t('elButton.refresh')"
					placement="top"
				>
					<el-button
						size="mini"
						circle
						icon="el-icon-refresh"
						@click="handleQuery"
					/>
				</el-tooltip>
				<el-tooltip
					class="item"
					effect="dark"
					:content="
						showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')
					"
					placement="top"
				>
					<el-button
						size="mini"
						circle
						icon="el-icon-search"
						@click="showSearch = !showSearch"
					/>
				</el-tooltip>
			</div>
		</el-row>

		<el-table
			v-loading="loading"
			:data="datasetList"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column
				:label="$t('equipment.number')"
				width="60"
				align="center"
				prop="id"
			/>
			<el-table-column :label="$t('calling.name')" align="center" prop="name" />
			<el-table-column
				:label="$t('dictionaries.dataStyle')"
				align="center"
				prop="type"
			>
				<template slot-scope="scope">
					<span v-if="scope.row.type === '数据库'"
						>{{ scope.row.type }}
						<el-tag v-if="scope.row.dbName">{{ scope.row.dbName }}</el-tag>
					</span>
					<span v-else
						>{{ scope.row.type }}
						<el-tag v-if="scope.row.apiMethod">{{
							scope.row.apiMethod
						}}</el-tag>
					</span>
				</template>
			</el-table-column>
			<el-table-column
				:label="$t('dictionaries.searchType')"
				align="center"
				prop="ftype"
			/>
			<el-table-column
				:label="$t('dictionaries.ipAddress')"
				align="center"
				prop="scripts"
				:show-overflow-tooltip="true"
			/>
			<el-table-column
				:label="$t('elButton.establishTime')"
				align="center"
				prop="createTime"
				width="180"
			>
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column
				:label="$t('equipment.control')"
				align="center"
				class-name="small-padding fixed-width"
				width="150"
				fixed="right"
			>
				<template slot-scope="scope">
					<el-button
						v-hasPerm="['dataset_edit']"
						size="mini"
						type="text"
						icon="el-icon-edit"
						@click="handleEdit(scope.row)"
						>{{ $t('elButton.change') }}
					</el-button>
					<el-button
						v-hasPerm="['dataset_del']"
						size="mini"
						type="text"
						icon="el-icon-delete"
						@click="handleDel(scope.row)"
						>{{ $t('elButton.delete') }}
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			:page.sync="queryParams.current"
			:limit.sync="queryParams.size"
			@pagination="getList"
		/>

		<!-- 添加或修改数据源对话框 -->
		<el-dialog
			:title="title"
			:visible.sync="open"
			:modal-append-to-body="true"
			:append-to-body="true"
			width="70%"
			:close-on-click-modal="false"
		>
			<el-form ref="form" :model="form" :rules="rules" label-width="120px">
				<el-row>
					<el-col :span="11">
						<el-form-item :label="$t('calling.name')" prop="name">
							<el-input
								v-model="form.name"
								:placeholder="$t('calling.nameInput')"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item :label="$t('dictionaries.dataStyle')" prop="type">
							<el-select
								v-model="form.type"
								:placeholder="$t('dictionaries.dataStyleSelect')"
								style="width:100%"
							>
								<el-option
									v-for="dict in typeOptions"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type === '数据库'" :span="11">
						<el-form-item :label="$t('database.name')">
							<el-select
								v-model="form.dbName"
								:placeholder="$t('database.nameInput')"
								style="width:100%"
							>
								<el-option
									v-for="dict in dbList"
									:key="dict.name"
									:label="dict.name"
									:value="dict.name"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type === '数据库'" :span="11">
						<el-form-item :label="$t('dictionaries.searchType')">
							<el-select
								v-model="form.ftype"
								:placeholder="$t('dictionaries.searchTypeSelect')"
								style="width:100%"
							>
								<el-option
									v-for="dict in ftypeOptions"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type === 'http请求'" :span="11">
						<el-form-item :label="$t('dictionaries.askStyle')">
							<el-select
								v-model="form.apiMethod"
								:placeholder="$t('dictionaries.askStyleInput')"
								style="width:100%"
							>
								<el-option
									v-for="dict in [
										{ label: 'POST', value: 'POST' },
										{ label: 'GET', value: 'GET' },
									]"
									:key="dict.value"
									:label="dict.label"
									:value="dict.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type === 'http请求'" :span="11">
						<el-form-item :label="$t('dictionaries.dataKey')">
							<el-tooltip
								class="item"
								effect="dark"
								:content="$t('dictionaries.format1')"
								placement="top-start"
							>
								<el-input
									v-model="form.dataKey"
									:placeholder="$t('dictionaries.dataKeyInput')"
								/>
							</el-tooltip>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type === 'http请求'" :span="11">
						<el-form-item :label="$t('dictionaries.errorKey')">
							<el-tooltip
								class="item"
								effect="dark"
								:content="$t('dictionaries.format2')"
								placement="top-start"
							>
								<el-input
									v-model="form.errorKey"
									:placeholder="$t('dictionaries.errorKeyInput')"
								/>
							</el-tooltip>
						</el-form-item>
					</el-col>
					<el-col v-if="form.type === 'http请求'" :span="11">
						<el-form-item :label="$t('dictionaries.successValue')">
							<el-tooltip
								class="item"
								effect="dark"
								:content="$t('dictionaries.format3')"
								placement="top-start"
							>
								<el-input
									v-model="form.successValue"
									:placeholder="$t('dictionaries.successValueInput')"
								/>
							</el-tooltip>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="数据源关联表名" prop="tables">
							<el-input v-model="form.tables" placeholder="多个以逗号隔开" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item :label="$t('dictionaries.ipAddress')" prop="scripts">
							<el-input
								v-model="form.scripts"
								type="textarea"
								rows="5"
								:placeholder="$t('dictionaries.ipAddressInput')"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item :label="$t('dictionaries.fields')" prop="fields">
							<el-button @click="fieldAdd">{{
								$t('dictionaries.add')
							}}</el-button>
							<el-table :data="fieldsList" style="margin-top:10px">
								<el-table-column label="key" align="center" prop="key">
									<template slot-scope="scope">
										<el-input v-model="scope.row.key" />
									</template>
								</el-table-column>
								<!-- <el-table-column label="别名" align="center" prop="alias">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.alias" />
                  </template>
                </el-table-column> -->
								<el-table-column
									:label="$t('calling.name')"
									align="center"
									prop="name"
								>
									<template slot-scope="scope">
										<el-input v-model="scope.row.name" />
									</template>
								</el-table-column>
								<el-table-column
									:label="$t('equipment.control')"
									align="center"
									class-name="small-padding fixed-width"
								>
									<template slot-scope="scope">
										<el-button
											size="mini"
											type="text"
											icon="el-icon-delete"
											@click="fieldDel(scope.row.key)"
										>
											{{ $t('dictionaries.remove') }}
										</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">{{
					$t('submitText')
				}}</el-button>
				<el-button @click="cancel">{{ $t('cancelText') }}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	listDataset,
	getDataset,
	delDataset,
	addDataset,
	editDataset,
	exportDataset,
} from '@/api/system/dataset'
import { datasourceList } from '@/api/toolkit/datasource'
// import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
	name: 'Dataset',
	components: {
		// Treeselect
	},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 总条数
			total: 0,
			// 数据源表格数据
			datasetList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 日期范围
			dateRange: [],
			typeOptions: [
				{ label: '数据库', value: '数据库' },
				{ label: 'http请求', value: 'http请求' },
			],
			// 数据库信息
			dbList: [],
			// 数据字段
			fieldsList: [],
			// 格式类型字典
			ftypeOptions: [
				{ label: '列表查询', value: 'queryForList' },
				{ label: '分页查询', value: 'queryForPage' },
				{ label: '单条查询', value: 'queryForOne' },
			],
			queryParams: {
				current: 1,
				size: 10,
				name: undefined,
				ftype: undefined,
				createTime: undefined,
			},
			// 显示搜索条件
			showSearch: true,
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				name: [
					{
						required: true,
						message: this.$t('database.dataSourceEmpty'),
						trigger: 'blur',
					},
				],
				scripts: [
					{
						required: true,
						message: this.$t('database.cantEmpty'),
						trigger: 'blur',
					},
				],
			},
		}
	},
	created() {
		this.getList()
		// this.getDicts('data_type').then(response => {
		//   this.ftypeOptions = response.data
		// })
		datasourceList().then((response) => {
			this.dbList = response.data
			this.dbList.push({ name: '默认' })
		})
		if (this.$route.params.handleAdd) {
			this.handleAdd()
		}
	},
	methods: {
		/** 查询数据源列表 */
		getList() {
			this.loading = true
			listDataset(this.addDateRange(this.queryParams, this.dateRange)).then(
				(response) => {
					this.datasetList = response.data
					this.total = response.total
					this.loading = false
				}
			)
		},
		// typeFormat(row, column) {
		//   return this.selectDictLabel(this.typeOptions, row.type)
		// },
		// // 格式类型字典翻译
		// ftypeFormat(row, column) {
		//   return this.selectDictLabel(this.ftypeOptions, row.ftype)
		// },
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				name: undefined,
				scripts: undefined,
				dbName: '默认',
			}
			this.resetForm('form')
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.current = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.dateRange = []
			this.resetForm('queryForm')
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		normalizer(node) {
			if (node.children && !node.children.length) {
				delete node.children
			}
			return {
				id: node.alias,
				label: node.name,
				children: node.children,
			}
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.fieldsList = []
			this.reset()
			this.open = true
			this.title = this.$t('database.addDataSource')
		},
		/** 修改按钮操作 */
		handleEdit(row) {
			this.reset()
			const id = row.id || this.ids
			if (row.fields) {
				this.fieldsList = JSON.parse(row.fields)
			}
			getDataset(id).then((response) => {
				this.form = response.data
				this.open = true
				this.title = this.$t('database.changeDataSource')
				this.$nextTick(() => {
					this.$refs.form.clearValidate()
				})
			})
		},
		/** 提交按钮 */
		submitForm: function() {
			this.$refs['form'].validate((valid) => {
				if (valid) {
					if (this.fieldsList.length > 0) {
						this.form.fields = JSON.stringify(this.fieldsList)
					}
					if (this.form.id !== undefined) {
						editDataset(this.form).then((response) => {
							if (response.code === 0) {
								this.msgSuccess(this.$t('loginLog.changeSuccess'))
								this.open = false
								this.getList()
							} else {
								this.msgError(response.msg)
							}
						})
					} else {
						addDataset(this.form).then((response) => {
							if (response.code === 0) {
								this.msgSuccess(this.$t('addSuccess'))
								this.open = false
								this.getList()
							} else {
								this.msgError(response.msg)
							}
						})
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDel(row) {
			const ids = row.id || this.ids
			this.$confirm(
				this.$t('database.deleteDataSource') +
					ids +
					this.$t('equipment.deleteEquipment2'),
				this.$t('warning'),
				{
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}
			)
				.then(function() {
					return delDataset(ids)
				})
				.then(() => {
					this.getList()
					this.msgSuccess(this.$t('deleteSuccess'))
				})
				.catch(function() {})
		},
		/** 导出按钮操作 */
		handleExport() {
			if (this.ids.length === 0) {
				this.msgWarning(this.$t('equipment.equipmentInput'))
				return
			}
			const queryParams = this.queryParams
			this.$confirm(this.$t('database.exportDataSource'), this.$t('warning'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'warning',
			})
				.then(() => {
					return exportDataset(queryParams, this.ids)
				})
				.then((response) => {
					this.download(response.data)
				})
				.catch(function() {})
		},
		/** 数据字段添加 */
		fieldAdd() {
			this.fieldsList.push({ key: '', name: '' })
		},
		/** 数据字段移除 */
		fieldDel(key) {
			const tempList = this.fieldsList
			this.fieldsList = []
			if (tempList.length > 0) {
				tempList.forEach((element) => {
					if (element.key !== key) {
						this.fieldsList.push(element)
					}
				})
			}
		},
	},
}
</script>
<style lang="scss" scoped>
.custom > .CodeMirror {
	height: auto;
	min-height: 200px;
}

.custom > .CodeMirror-scroll {
	min-height: 200px;
}

.custom > .cm-s-rubyblue span.cm-string {
	color: #f08047;
}
</style>
